package com.leetcode;

import com.leetcode.common.ListNode;

import static com.leetcode.util.LinkedListUtil.createList;
import static com.leetcode.util.LinkedListUtil.printList;

/**
 * 234. 回文链表
 * 快慢指针
 *
 * @author fy
 * @date 2022/4/11 21:11
 */
public class Solution234 {

    public boolean isPalindrome(ListNode head) {
        // 如果为null或者只有一个节点, 肯是回文链表
        if (head == null || head.next == null) {
            return true;
        }
        // 找到中间节点, 切成两个链
        ListNode mid = middleNode(head);
        ListNode l1 = head;
        ListNode l2 = mid.next;
        // 切断联系
        mid.next = null;
        // 反转后一个链
        l2 = reverseList(l2);
        while (l1 != null && l2 != null) {
            if (l1.val != l2.val) {
                return false;
            }
            l1 = l1.next;
            l2 = l2.next;
        }
        return true;
    }

    /**
     * 找到中间节点的前一个节点
     *
     * @param head
     * @return
     */
    private ListNode middleNode(ListNode head) {
        ListNode fast = head;
        ListNode slow = head;
        while (fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }

    /**
     * 反转链表
     *
     * @param head
     * @return
     */
    private ListNode reverseList(ListNode head) {
        ListNode pre = null;
        ListNode p = head;
        while (p != null) {
            ListNode next = p.next;
            p.next = pre;

            pre = p;
            p = next;
        }
        return pre;
    }

    public static void main(String[] args) {
        ListNode head = createList(new int[]{1, 2, 2, 1});
        printList(head);
        new Solution234().isPalindrome(head);
        printList(head);
    }

}
